package com.cuckoo.service.impl;

import com.cuckoo.common.JsonData;
import com.cuckoo.dao.UserMapper;
import com.cuckoo.exception.CuckooException;
import com.cuckoo.pojo.AuthCode;
import com.cuckoo.pojo.User;
import com.cuckoo.service.AuthCodeService;
import com.cuckoo.service.UserService;
import com.cuckoo.util.MD5;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthCodeService authCodeService;

    @Override
    public Integer addUser(User user,String code) throws Exception {
        //验证短信
        AuthCode authCode=authCodeService.getAuthCodeByPhoneAndCodeAndType ( user.getPhone (),code,1 );
        if (authCode==null){
            throw new CuckooException ( "短信验证码不存在!");
        }
        //判断用户名或者手机号是否存在
        User authUser=findUserByNameOrPhone ( user.getPhone () );
        if (authUser!=null){
            throw new CuckooException ( "手机已经存在" );
        }
        authUser=findUserByNameOrPhone ( user.getUsername () );
        if (authUser!=null){
            throw new CuckooException ( "此用户名已经存在" );
        }
        user.setPassword ( MD5.md5 ( user.getPassword () ) );
        return userMapper.insertSelective (user);
    }

    @Override
    public User findUserByNameOrPhone(String info) {
        //log.info ( "已经进入" );
        return userMapper.findUserByNameOrPhone ( info );
    }
}
